<?php


namespace app\common\service\coupon\sync_channel;


use api\channel\jutuike\Coupon;
use api\coupon\Jutuike;
use app\model\CouponBrand;
use app\model\CouponBrandCateRelation;
use app\model\CouponCate;
use app\model\CouponProduct;
use app\model\CouponProductChannel;use think\Exception;use think\facade\Log;

class JutuikeChannel extends Base
{

    /**
     * @var Jutuike $jutuike 聚推客具体请求接口
     */
    public $jutuike;

    public function __construct()
    {
        $this->jutuike = new Coupon();

        $this->supplier = $this->jutuike->supplierInfo;
    }

    function getCate(): array
    {
        $categorys = $this->jutuike->category();
        Log::info('聚推客获取分类'.json_encode($categorys));
        if (empty($categorys)){
            throw new Exception('请稍后再同步');
        }
        $result = [];
        foreach ($categorys as $category) {
            $temp = [];
            $temp['origin_id'] = $category['id'] ?? '';//可为空
            $temp['name'] = $category['name'];
            $result[] = $temp;
        }

        $this->cates = $result;
        return $result;
    }

    /**
     * 获取品牌
     */
    function getBrand()
    {
        //商品保存同事保存品牌

    }

    /**
     * 获取产品
     * @return mixed
     */
    function getProduct()
    {

        foreach ($this->cates as $item) {

            for ($i = 1; $i < 100; $i++) {
                $products = $this->jutuike->productList($item['origin_id'], $i);
                foreach ($products['data'] as $product) {
                    $product['supplier_id'] = $this->supplier->id;
                    $product['origin_id'] = $product['product_id'] ?? 0;
                    $product['market_price'] = yuan2fen($product['official_price']) ?? 0;
                    $product['cost_price'] = yuan2fen($product['sell_price']) ?? 0;
                    $product['sale_price'] = yuan2fen($product['sell_price']) ?? 0;
                    $product['extend'] = json_encode($product);
                    $this->products[] = $product;
                }
                if ($i >= $products['last_page']) break;
            }
//            break;//上线删除
        }

        return $this->products;

    }


    /**
     * 保存产品
     */
    public function saveProduct()
    {

        //保存商品渠道&& 保存商品 第一次开发数据可以这样处理，后面需要严格处理渠道对应商品

        foreach ($this->products as $product) {
            //品牌
            $couponBrandObj = CouponBrand::findOrCreate(['mark' => $product['icon']]);
            if (empty($couponBrandObj->image_url)) $couponBrandObj->save(['image_url' => $product['icon']]);

            if (empty($couponBrandObj->name)) $couponBrandObj->save(['name' => $product['name']]);

            //分类有多个品牌
            $cateIds = explode(',',$product['cid']);

            foreach ($cateIds as $cateId) {
                $couponCate = CouponCate::where(['mark' =>$cateId])->find();
                if (!$couponCate) continue;
                CouponBrandCateRelation::findOrCreate(['brand_id' => $couponBrandObj->id,'cate_id' =>$couponCate->id]);
            }


            $productObj =CouponProduct::findOrCreate(['name' =>$product['name'],'mark' => $product['product_id'],'brand_id' => $couponBrandObj->id]);
            //需要关联品牌，品牌挂钩分类

            $product['product_id'] =$productObj->id;
            $couponProductChannel = CouponProductChannel::findOrCreate(
                [
                    'name' =>$product['name'],'supplier_id' => $product['supplier_id']
                ]
            );
            $couponProductChannel->save($product);
        }

        $this->brandName();
    }

    /**
     * 品牌名称
     */
    public function brandName() {
        // 可优化
        // https://webapi.jutuike.com/wap/productList?code=Vg569zlf

        $matchArr = ['美团', '饿了么', '腾讯体育', '乐视', 'QQ音乐', '网易云音乐', '瑞幸咖啡', '奈雪の茶', '三只松鼠',
            '一起学语文', '脉脉', '青桔', '达龙云电脑', 'e袋洗', 'QQ会员'
        ];  // 特殊匹配
        $filterArr = ['黄金会员', '普通会员', '影视会员', '超级会员', '白金会员', '盐选会员', '豪华会员', '豪华VIP',
            'VIP', '会员',
        ];  // 注意顺序 需要过滤的名称

        // 读取品牌表
        $couponBrandModel = CouponBrand::column('name','id');
        $update = [];
        foreach ($couponBrandModel as $id => $name) {
            $newName = '';
            foreach ($matchArr as $matchField) {
                if (strpos($name, $matchField) !== false) {
                    $newName = $matchField;
                    break;
                }
            }
            if (!$newName) {
                foreach ($filterArr as $filterFiled) {
                    $index = strpos($name, $filterFiled);
                    if ($index !== false) {
                        $delName = mb_strstr($name, $filterFiled);  // 找到会员相关的
                        $newName = str_replace($delName, '', $name);  // 剔除不必要的
                        break;
                    }
                }
            }
            if ($newName && $newName != $name) {
                $update[] = [
                    'id' => $id,
                    'name' => $newName,
//                'old_name' => $name,
                ];
            }

        }
        if ($update) {
            // 批量更新品牌名称
            $brandModel = new CouponBrand();
            $brandModel->saveAll($update);
        }
    }


    function getChannelProduct()
    {
        //暂无需开发
    }

    function getType()
    {
        //暂无需开发
    }
}